package com.credit.web.basic;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.persistence.SearchDataTransform;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.credit.context.CreditServletContext;
import com.credit.entity.CreditMessageEntity;
import com.credit.entity.CreditUserInfo;
import com.credit.exception.ErrorException;
import com.credit.service.CreditMessageService;
import com.credit.service.RedisService;
import com.credit.util.BeanToMapUtil;
import com.credit.util.Constants;
import com.credit.util.ParamsConstant;
import com.credit.util.SendVerifyCodeCase;
import com.credit.web.basic.bean.ResBean;


@Controller
@RequestMapping("/sms")
public class SMessageController {
	private static final Log log = LogFactory.getLog(SMessageController.class);

	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	@Autowired
	private RedisService redisService;
	
	@ResponseBody
	@RequestMapping(value = "/sendCode")
	public void login(HttpServletRequest request, HttpServletResponse response, @RequestParam("mobile") String mobile,
			@RequestParam("graCode") String graCode,String timestamp)
			throws ErrorException, IllegalArgumentException, IllegalAccessException, ClientException {

		if (StringUtils.isEmpty(mobile)) {
			throw new ErrorException(Constants.MOBILE_NOTNULL_ERROR_CODE, Constants.MOBILE_NOTNULL_ERROR_DESC);
		}
		
		if(StringUtils.isEmpty(graCode)){
			throw new ErrorException(Constants.GRACODE_NOTNULL_ERROR_CODE, Constants.GRACODE_NOTNULL_ERROR_DESC);
		}
		
		if(StringUtils.isEmpty(timestamp)){
			throw new ErrorException(Constants.TIMESTAMP_NOTNULL_ERROR_CODE, Constants.TIMESTAMP_NOTNULL_ERROR_DESC);
		}
		
		//安全限制 1，短信设置每隔60秒，2、ip/mac限制，3、图形验证码
		if(!graCode.equals(SendVerifyCodeCase.getRegisterVerifyCode(ParamsConstant.GRA_CODE_CACHE_PREFIX, timestamp))){
			throw new ErrorException(Constants.GRACODE_VERIFY_ERROR_CODE, Constants.GRACODE_VERIFY_ERROR_DESC);
		}
		Date nowDate = new Date();
		String dateStr = sdf.format(nowDate);
		
		Set<Object> set = redisService.getForZSet(ParamsConstant.SMS_CODE_TIME_LIMIT, mobile+"_"+dateStr, true);
		if(set!=null){
			if(set.size()>=10){
				throw new ErrorException(Constants.SMS_LIMIT_ERROR_CODE, Constants.SMS_LIMIT_ERROR_DESC);
			}
		
			for(Object object:set){
				
				String timeStr = (String) object;
				long differ = (nowDate.getTime()-Long.valueOf(timeStr))/1000;
				if(differ<=60){
					throw new ErrorException(Constants.MINUTE_LIMIT_ERROR_CODE, Constants.MINUTE_LIMIT_ERROR_DESC);
				}
			    break;
			}
			
/*			set.forEach(item->{
				
				String timeStr = (String) item;
				long differ = (nowDate.getTime()-Long.valueOf(timeStr))/1000;
				if(differ<=60){
					throw new ErrorException(Constants.MINUTE_LIMIT_ERROR_CODE, Constants.MINUTE_LIMIT_ERROR_DESC);
				}
				return;
			});*/
			
		}
		
		long currentTime = System.currentTimeMillis();
		redisService.saveForZSet(ParamsConstant.SMS_CODE_TIME_LIMIT, mobile+"_"+dateStr, String.valueOf(currentTime), currentTime);
		
	    //设置超时时间-可自行调整
	    System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
	    System.setProperty("sun.net.client.defaultReadTimeout", "10000");
	    //初始化ascClient需要的几个参数
	    final String product = "Dysmsapi";//短信API产品名称
	    final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名
	    //替换成你的AK
	    final String accessKeyId = "LTAIwLI8QWEVRl1O";//你的accessKeyId,参考本文档步骤2
	    final String accessKeySecret = "6KMix1dat3GAutmnCn3c6TSeTwNgwI";//你的accessKeySecret，参考本文档步骤2
	    //初始化ascClient,暂时不支持多region
	    IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
	    accessKeySecret);
	    DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
	    IAcsClient acsClient = new DefaultAcsClient(profile);
	     //组装请求对象
	     SendSmsRequest smsRequest = new SendSmsRequest();
	     //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
	     smsRequest.setPhoneNumbers(mobile);
	     //必填:短信签名-可在短信控制台中找到
	     smsRequest.setSignName("熊猫贷款");
	     //必填:短信模板-可在短信控制台中找到
	     smsRequest.setTemplateCode("SMS_75780045");
	     //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
	     smsRequest.setTemplateParam("{\"code\":\""+SendVerifyCodeCase.genRegisterVerifyCode(ParamsConstant.SMS_CODE_CACHE_PREFIX,mobile)+"\"}");
	     //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
	     smsRequest.setOutId("yourOutId");
	    //请求失败这里会抛ClientException异常
	    SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(smsRequest);
	    
	    log.info("收到短信发送接口通知:"+sendSmsResponse.getMessage()+","+sendSmsResponse.getCode());
	    if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
	        //请求成功
	    	log.info(sendSmsResponse.getMessage());
	    	
	    }else{
	    	throw new ErrorException(Constants.SMS_SEND_ERROR_CODE, Constants.SMS_SEND_ERROR_DESC);
	    }
		
		ResBean resBean = CreditServletContext.getResBean();
		
		CreditServletContext.setResBean(resBean);
	} 
	


}
